<template>
  <lb-layout
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <lb-table
      :column="tableData.column"
      :data="tableData.data"
      pagination
      background
      border
      height="700"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[20, 40, 60, 80]"
      :pager-count="5"
      :current-page.sync="currentPage"
      :total="total"
      :page-size="pageSize"
      @size-change="handleSizeChange"
      @p-current-change="handleCurrentChange"
    >
    </lb-table>
    <!-- 反馈对话框 -->
    <el-dialog
      title="反馈意见"
      :visible.sync="show2"
      width="500px"
      append-to-body
    >
      <el-form ref="form2" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="反馈意见" prop="content">
          <el-input type="textarea" v-model="form.content"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          v-hasPermi="['energy:opinion:add']"
          type="primary"
          @click="feedback"
          >确 定</el-button
        >
        <el-button @click="close('form2')">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 手工调整额度对话框 -->
    <el-dialog
      title="手工调整额度"
      :visible.sync="show"
      width="500px"
      append-to-body
    >
      <el-form ref="form3" :model="model" :rules="rules" label-width="100px">
        <el-form-item label="引导值" prop="adjustGuideVal">
          <el-input-number v-model="model.adjustGuideVal" />
        </el-form-item>
        <el-form-item label="基准值" prop="adjustBaseVal">
          <el-input-number v-model="model.adjustBaseVal" />
        </el-form-item>
        <el-form-item label="约束值" prop="adjustConstraintVal">
          <el-input-number v-model="model.adjustConstraintVal" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="close('form')">取 消</el-button>
      </div>
    </el-dialog>
    <exports
      :visible.sync="exportsShow"
      @close="hanleClose"
      @input="setImportDataId"
    ></exports>
    <detail :id="id" :visible.sync="detailShow" @close="close"></detail>
  </lb-layout>
</template>

<script>
import {
  checkCommitEnable,
  quotaAllocation,
  quotaAllocationOpinion,
  adjustVal,
  totalEnergy,
} from "@/api/quota/allocation";
import auth from "@/plugins/auth";
import { rationVersionList } from "@/api/quota/energy";
import CascaderSelect from "@/components/Select/CascaderSelect";
import { exportExecl } from "@/utils/export-execl";
import exports from "@/views/work/quota/energy/components/exports.vue";
import { mul, formatDate } from "@/utils/index";
import detail from "@/views/work/quota/allocation/components/detail.vue";
export default {
  name: "allDistribution",
  filters: {
    dictFee(val) {
      const text = val ? mul(val, 100) + "%" : "";
      return text;
    },
    formatTime(val) {
      const text = val ? formatDate(val) : "";
      return text;
    },
  },
  dicts: ["energy_type", "target_type"],
  components: { CascaderSelect, exports, detail },
  data() {
    return {
      id: "",
      detailShow: false,
      // isNhgl: false, //用能单位领导
      // isYnbm: false, //用能人员
      show: false,
      show2: false,
      exportsShow: false,
      versionOption: [],
      currentPage: 1,
      pageSize: 20,
      total: 0,
      apsForm: {
        formRef: "form",
        labelWidth: "120px",
        formData: {},
        formConfig: {
          formAttr: {
            inline: true,
            size: "small",
          },
          properties: {
            //这里是渲染查询表单的表头和类型的数据
            sysDeptId: {
              typeName: "el-select",
              render: (h) => {
                let that = this;
                return (
                  <div>
                    <CascaderSelect
                      values={that.$refs?.form?.getFieldsValue().sysDeptId}
                      value={that.$refs?.form?.getFieldsValue().sysDeptId}
                      varient={"energy"}
                      size={"small"}
                      placeholder={"用能单位"}
                      onInput={that.handlerLiandong}
                    ></CascaderSelect>
                  </div>
                );
              },
            },
            rationCriterionVersion: {
              typeName: "el-select",
              display: true,
              render: (h) => {
                let that = this;
                // 数据严谨处理,处理后端数据异常情况
                let valNum =
                  that.$refs?.form?.getFieldsValue().rationCriterionVersion;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "额度标准版本号",
                        value: valNum,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue(
                            "rationCriterionVersion",
                            value
                          );
                        },
                      },
                    },
                    [
                      that.versionOption.map((item) => {
                        return h("el-option", {
                          props: {
                            label: item,
                            value: item,
                            key: item,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            energyType: {
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.energy_type.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().energyType;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "能耗种类",
                        value: valNum,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("energyType", value);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            targetType: {
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.target_type.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().targetType;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "指标类型",
                        value: valNum,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("targetType", value);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            allocationYear: {
              typeName: "el-date-picker",
              type: "year",
              "value-format": "yyyy",
              placeholder: "额度分配年份",
            },
          },
          formSoltButton: [
            {
              label: "搜索",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-search",
              display: true,
              click: this.handlerSearchDetail,
            },
            {
              label: "重置",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-refresh-left",
              display: true,
              click: this.handleReset,
            },
            // {
            //   label: "额度批量分配",
            //   type: "primary",
            //   typeName: "el-button",
            //   plain: true,
            //   size: "small",
            //   display: true,
            //   click: () => this.distribution(),
            // },
            // {
            //   label: "导入实际能耗",
            //   type: "primary",
            //   typeName: "el-button",
            //   plain: true,
            //   size: "small",
            //   display: true,
            //   click: () => (this.exportsShow = true),
            // },
            {
              label: "导出",
              type: "warning",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-upload2",
              plain: true,
              display: true,
              click: () => this.handleExport(),
            },
          ],
        },
      },
      tableData: {
        column: [
          {
            label: "所属用能单位",
            prop: "sysDeptName",
            minWidth: 150,
            showOverflowTooltip: true,
          },
          {
            label: "能耗分配年度",
            prop: "allocationYear",
            width: 130,
            showOverflowTooltip: true,
          },
          // {
          //   prop: "rationCriterionVersion",
          //   label: "版本号",
          //   showOverflowTooltip: true,
          //   minWidth: 150,
          // },
          {
            prop: "allocationBaseVal",
            label: "能耗实际分配额度N（kwh/m2）",
            width: 240,
            showOverflowTooltip: true,
          },
          {
            prop: "area",
            label: "用能面积（m2）",
            width: 140,
            showOverflowTooltip: true,
          },
          {
            prop: "userNum",
            label: "用能人数（p）",
            width: 140,
          },
          {
            prop: "allocationBaseValLastYear",
            label: "上年额度（kgce/m2）",
            width: 180,
          },
          {
            prop: "energyValLastYear",
            label: "上年实际能耗（kgce/m2）",
            width: 220,
            showOverflowTooltip: true,
          },
          // {
          //   prop: "energyType",
          //   label: "能耗种类",
          //   minWidth: 150,
          //   align: "center",
          //   render: (h, scope) => {
          //     return (
          //       <div>
          //         <dict-tag
          //           options={this.dict.type.energy_type}
          //           value={scope.row.energyType}
          //         />
          //       </div>
          //     );
          //   },
          // },
          // {
          //   prop: "targetType",
          //   label: "指标类型",
          //   minWidth: 150,
          //   align: "center",
          //   render: (h, scope) => {
          //     return (
          //       <div>
          //         <dict-tag
          //           options={this.dict.type.target_type}
          //           value={scope.row.targetType}
          //         />
          //       </div>
          //     );
          //   },
          // },
          {
            prop: "content",
            label: "反馈信息",
            minWidth: 150,
            showOverflowTooltip: true,
          },
          // {
          //   prop: "declareContent",
          //   label: "分配状态",
          //   width: 150,
          //   showOverflowTooltip: true,
          // },
          {
            label: "操作",
            width: "160",
            fixed: "right",
            render: (h, scope) => {
              let a, b, c;
              if (
                auth.hasPermi("energy:opinion:add") &&
                scope.row.opinionEnable
              ) {
                a = (
                  <el-button
                    type="text"
                    size="small"
                    icon="el-icon-edit"
                    onClick={() => {
                      this.show2 = true;
                      this.id = scope.row.id;
                    }}
                  >
                    反馈
                  </el-button>
                );
              } else {
                a = <div style="display:none"></div>;
              }
              // if (
              //   scope.row.editEnable &&
              //   auth.hasPermi("energy:allocation:edit")
              // ) {
              //   b = (
              //     <el-button
              //       type="text"
              //       size="small"
              //       icon="el-icon-edit"
              //       onClick={() => {
              //         this.handleUpdate(scope.row);
              //       }}
              //     >
              //       调整额度
              //     </el-button>
              //   );
              // }
              c = (
                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-view"
                  onClick={() => {
                    this.detail(scope.row.id);
                  }}
                >
                  详情
                </el-button>
              );
              return (
                <div>
                  {a}
                  {b}
                  {c}
                </div>
              );
            },
          },
        ],
        data: [],
      },
      // 弹出层标题
      title: "",
      model: {
        adjustGuideVal: 0,
        adjustBaseVal: 0,
        adjustConstraintVal: 0,
      },
      form: {
        content: "",
      },
      rules: {
        content: [
          {
            required: true,
            message: "请输入反馈意见",
          },
        ],
        adjustBaseVal: [
          {
            required: true,
            message: "请输入基准值",
            trigger: ["change", "blur"],
          },
        ],
        adjustGuideVal: [
          {
            required: true,
            message: "请输入引导值",
            trigger: ["change", "blur"],
          },
        ],
        adjustConstraintVal: [
          {
            required: true,
            message: "请输入约束值",
            trigger: ["change", "blur"],
          },
        ],
      },
    };
  },
  created() {
    this.getVersionList();
    this.judgeRole();
  },
  methods: {
    judgeRole() {
      // if (auth.hasPermi("energy:allocation:quotaAllocation")) {
      //   this.apsForm.formConfig.formSoltButton[2].display = false;
      // }
      // if (auth.hasPermi("energy:assess:import")) {
      //   this.apsForm.formConfig.formSoltButton[3].display = false;
      // }
      // 额度标准版本号
      if (auth.hasPermi("energy:criterion:versionList")) {
        this.apsForm.formConfig.properties.rationCriterionVersion.display = false;
      }
      // 导出
      if (auth.hasPermi("energy:allocation:export")) {
        this.apsForm.formConfig.formSoltButton[2].display = false;
      }
      // 搜索
      if (auth.hasPermi("energy:allocation:list")) {
        this.apsForm.formConfig.formSoltButton[0].display = false;
        this.apsForm.formConfig.formSoltButton[1].display = false;
      }
      // if (auth.hasRole("ynbm_leader") || auth.hasRole("ynbm_user")) {
      //   this.isYnbm = true;
      // }
      // if (auth.hasRole("nhgl_user") || auth.hasRole("nhgl_leader")) {
      //   this.isNhgl = true;
      // }
      this.handlerSearchDetail();
    },
    handleUpdate(row) {
      this.model = row;
      this.show = true;
    },
    handlerLiandong(val) {
      let result;
      if (val && val.length > 0) {
        result = val[val.length - 1];
      } else {
        result = null;
      }
      this.$refs?.form?.setFieldValue("sysDeptId", result);
    },
    async initData(currentPage, pageSize, data) {
      let that = this;
      let query = {
        ...data,
      };
      if (currentPage) {
        query.pageNum = currentPage;
      } else {
        query.pageNum = that.currentPage;
      }
      if (pageSize) {
        query.pageSize = pageSize;
      } else {
        query.pageSize = that.pageSize;
      }
      that.$store.commit("app/updateApiCount", "add");
      await totalEnergy(query)
        .then((res) => {
          that.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            that.$message.warning(res.msg);
            return false;
          }
          that.tableData.data = res.rows;
          that.total = res.total;
        })
        .catch((err) => {
          that.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!300081");
        });
    },
    handlerSearchDetail(val) {
      //val===1 删除操作成功后分页边界值处理
      let currentPage = 1;
      if (val === 1) {
        if (
          this.total === (this.currentPage - 1) * this.pageSize + 1 &&
          this.total !== 0 &&
          this.currentPage > 1
        ) {
          currentPage = this.currentPage - 1;
          this.currentPage = currentPage;
        } else {
          currentPage = this.currentPage;
        }
      } else {
        currentPage = this.currentPage;
      }
      const data = {
        ...this.$refs?.form?.getFieldsValue(),
      };
      this.initData(currentPage, this.pageSize, data);
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.handlerSearchDetail();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handlerSearchDetail();
    },
    handleReset() {
      //重置
      this.$refs?.form?.resetFields();
      this.handlerSearchDetail();
    },
    // headerRowStyle(obj) {
    //   if (
    //     obj.column.property === "allocationGuideVal" ||
    //     obj.column.property === "allocationBaseVal" ||
    //     obj.column.property === "allocationConstraintVal"
    //   ) {
    //     return "tabel-bg-blue";
    //   } else if (
    //     obj.column.property === "adjustGuideVal" ||
    //     obj.column.property === "adjustBaseVal" ||
    //     obj.column.property === "adjustConstraintVal" ||
    //     obj.column.property === "caozuo"
    //   ) {
    //     return "tabel-bg-red";
    //   } else if (
    //     obj.column.property === "assessGuideVal" ||
    //     obj.column.property === "assessBaseVal" ||
    //     obj.column.property === "assessConstraintVal"
    //   ) {
    //     return "tabel-bg-green";
    //   }
    // },
    // tableHeaderCellStyle({ row, column, rowIndex, columnIndex }) {
    //   if (columnIndex === 2) {
    //     return "background:rgba(223,240,216,0.4)";
    //   } else if (columnIndex === 3) {
    //     return "background:rgba(242,222,222,0.4)";
    //   } else if (columnIndex === 4) {
    //     return "background:rgba(217,237,247,0.4)";
    //   }
    // },
    // objectSpanMethod({ row, column, rowIndex, columnIndex }) {
    //   if (columnIndex > 6) {
    //     if (rowIndex % this.list.length === 0) {
    //       return {
    //         rowspan: this.list.length,
    //         colspan: 1,
    //       };
    //     } else {
    //       return {
    //         rowspan: 0,
    //         colspan: 0,
    //       };
    //     }
    //   }
    // },
    hanleClose() {
      this.exportsShow = false;
    },
    setImportDataId(data) {
      this.$refs?.form?.setFieldValue("importDataId", data);
      this.handlerSearchDetail();
    },
    //获取版本号
    getVersionList() {
      rationVersionList()
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.versionOption = res.data;
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!300064");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const data = {
        ...this.$refs?.form?.getFieldsValue(),
      };
      exportExecl("额度分配", "/energy/quota-allocation/export", data, this);
    },
    detail(id) {
      this.id = id;
      this.detailShow = true;
    },
    /** 额度批量分配 */
    distribution() {
      const data = this.$refs?.form.getFieldsValue();
      if (!data.sysDeptId) {
        this.$message.warning("请选择用能单位");
        return false;
      }
      if (!data.energyType) {
        this.$message.warning("请选择能耗种类");
        return false;
      }
      if (!data.targetType) {
        this.$message.warning("请选择指标类型");
        return false;
      }
      if (!data.rationCriterionVersion) {
        this.$message.warning("请选择额度标准版本号");
        return false;
      }
      if (!data.allocationYear) {
        this.$message.warning("请选择额度分配年份");
        return false;
      }
      quotaAllocation(data)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("操作成功");
          this.handleReset();
        })
        .catch((err) => {
          this.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!300072");
        });
    },
    handleUpdate(row) {
      this.model = row;
      this.show = true;
    },
    close(name) {
      this.resetForm(name);
      this.show = false;
      this.show2 = false;
      this.detailShow = false;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form3"].validate((valid) => {
        if (valid) {
          const data = {
            ...this.$refs?.form?.getFieldsValue(),
            adjustBaseVal: this.model.adjustBaseVal,
            adjustConstraintVal: this.model.adjustConstraintVal,
            adjustGuideVal: this.model.adjustGuideVal,
            id: this.model.id,
          };
          adjustVal(data)
            .then((res) => {
              if (res.code === 700) {
                this.$message.warning(res.msg);
                return false;
              }
              this.$message.success("操作成功");
              this.close("form");
              this.handlerSearchDetail();
            })
            .catch((err) => {
              this.$store.commit("app/updateApiCount");
              // this.$message.error("系统错误,请联系管理员!300075");
            });
        }
      });
    },
    //反馈
    feedback() {
      this.$refs["form2"].validate((valid) => {
        if (valid) {
          const data = {
            quotaAllocationId: this.id,
            content: this.form.content,
          };
          quotaAllocationOpinion(data)
            .then((res) => {
              if (res.code === 700) {
                this.$message.warning(res.msg);
                return false;
              }
              this.$message.success("操作成功");
              this.close("form2");
              this.handlerSearchDetail();
            })
            .catch((err) => {
              this.$store.commit("app/updateApiCount");
              // this.$message.error("系统错误,请联系管理员!300074");
            });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .tabel-bg-green {
  background: rgba(223, 240, 216, 0.4) !important;
}

::v-deep .tabel-bg-blue {
  background: rgba(217, 237, 247, 0.4) !important;
}

::v-deep .tabel-bg-red {
  background: rgba(242, 222, 222, 0.4) !important;
}

.flex {
  display: flex;
  justify-content: center;
  align-items: center;

  .el-icon-info {
    font-size: 18px;
    padding-left: 10px;
    vertical-align: text-bottom;
    cursor: pointer;
  }
}

.box-card {
  .clearfix {
    height: 22px;
    width: 100%;
    z-index: 99;

    span {
      opacity: 0.8;
    }
  }

  span {
    &:nth-child(1) {
      font-size: 20px;
      font-weight: 600;
      color: #333333;
    }
  }

  .constip {
    display: flex;
    align-items: center;

    .cons-tabs {
      margin-right: 20px;
    }
  }

  .unit {
    span {
      font-weight: 400;
      font-size: 14px;
      font-style: normal;
      letter-spacing: 0;
      text-decoration: none;

      &:nth-child(1) {
        color: rgb(16, 16, 16);
        margin-right: 10px;
      }

      &:nth-child(2) {
        color: rgb(247, 122, 5);
      }
    }
  }
}
</style>
